import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

// 解决ES模块中__dirname未定义的问题
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 右侧对齐输出函数
const logRight = (msg, type = 'info') => {
    const padLength = Math.max(0, (process.stdout.columns || 80) - msg.length - 4);
    const pad = ' '.repeat(padLength);
    const prefix = type === 'error' ? '❌ ' : '✅ ';
    console.log(`${pad}${prefix}${msg}`);
};

// 1. 读取 package.json
let pkgConfig;
try {
    const pkgPath = path.resolve(__dirname, '../package.json');
    pkgConfig = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
} catch (err) {
    logRight(`读取 package.json 失败：${err.message}`, 'error');
    process.exit(1);
}

// 2. 提取入口路径
const entryPaths = [];
pkgConfig.main && entryPaths.push(pkgConfig.main);
pkgConfig.module && entryPaths.push(pkgConfig.module);
if (pkgConfig.exports && typeof pkgConfig.exports === 'object') {
    const collectExports = (obj) => {
        Object.values(obj).forEach(v =>
            typeof v === 'string' ? entryPaths.push(v) : typeof v === 'object' && collectExports(v)
        );
    };
    collectExports(pkgConfig.exports);
}
const uniqueEntries = [...new Set(entryPaths)].filter(p => p && !p.startsWith('http'));

if (uniqueEntries.length === 0) {
    logRight('package.json 未配置任何入口（main/module/exports）', 'error');
    process.exit(1);
}

// 3. 校验入口文件
let hasError = false;
logRight('开始验证打包产物...');
logRight('-------------------');

uniqueEntries.forEach(entry => {
    const absPath = path.resolve(__dirname, '../', entry);
    if (fs.existsSync(absPath)) {
        const isEmpty = fs.statSync(absPath).size === 0;
        if (isEmpty) {
            logRight(`空文件：${entry}`, 'error');
            hasError = true;
        } else {
            logRight(`存在：${entry}`);
        }
    } else {
        logRight(`缺失：${entry}`, 'error');
        hasError = true;
    }
});

// 4. 校验输出目录
const outDir = pkgConfig.build?.outDir || 'cesium-gis-vue3';
const outDirAbsPath = path.resolve(__dirname, '../', outDir);
if (!fs.existsSync(outDirAbsPath)) {
    logRight(`输出目录缺失：${outDir}`, 'error');
    hasError = true;
} else {
    logRight(`输出目录存在：${outDir}`);
}

// 5. 最终结果
logRight('-------------------');
if (hasError) {
    logRight('打包验证失败！修复后重试', 'error');
    process.exit(1);
} else {
    logRight('所有产物验证通过！可正常使用');
    process.exit(0);
}
